<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import gameService from '../services/gameService'
import type { Soup, Message } from '../types'

const route = useRoute()
const router = useRouter()
const soupId = computed(() => route.params.id as string)

const soup = ref<Soup | null>(null)
const loading = ref(true)
const error = ref('')
const messages = ref<Message[]>([])
const inputMessage = ref('')
const maxTurns = 20
const currentTurn = ref(1)
const gameStatus = ref<'playing' | 'won' | 'lost'>('playing')
const showSolution = ref(false)

// 获取海龟汤详情
const fetchSoupDetail = async () => {
  loading.value = true
  error.value = ''
  
  try {
    // 模拟获取海龟汤详情
    soup.value = {
      id: soupId.value,
      title: '神秘的敲门声',
      description: '一个寒冷的夜晚，突然传来一阵急促的敲门声...',
      solution: '其实敲门的是小明的邻居，他看到小明家的窗户没关，担心有小偷，所以来提醒小明。',
      difficulty: 'medium',
      category: 'mystery',
      playerCount: 128,
      completionRate: 78
    }
    
    // 初始化游戏消息
    messages.value = [
      {
        id: '1',
        content: `欢迎来到海龟汤游戏！\n今天的题目是：${soup.value.description}\n你可以通过提问来推测真相，我只能回答"是"、"否"或"无关"。\n开始你的推理吧！`,
        sender: 'ai',
        timestamp: new Date().toISOString()
      }
    ]
  } catch (err: any) {
    error.value = err.message || '获取海龟汤详情失败'
  } finally {
    loading.value = false
  }
}

// 发送问题
const sendQuestion = async () => {
  if (!inputMessage.value.trim() || currentTurn.value > maxTurns || gameStatus.value !== 'playing') {
    return
  }
  
  const question = inputMessage.value.trim()
  inputMessage.value = ''
  
  // 添加用户消息
  const userMessage: Message = {
    id: Date.now().toString(),
    content: question,
    sender: 'user',
    timestamp: new Date().toISOString()
  }
  messages.value.push(userMessage)
  
  // 模拟AI回答
  setTimeout(() => {
    generateAIResponse(question)
  }, 1000)
}

// 生成AI回答
const generateAIResponse = (question: string) => {
  // 这里应该是调用AI服务，但为了演示，我们使用一些规则来生成回答
  let aiResponse = '否'
  
  // 简单的关键词匹配规则
  const positiveKeywords = ['邻居', '窗户', '提醒', '寒冷', '夜晚']
  const negativeKeywords = ['小偷', '危险', '鬼', '外星人', '谋杀']
  const irrelevantKeywords = ['天气', '食物', '电影', '游戏', '体育']
  
  const lowerQuestion = question.toLowerCase()
  
  // 检查关键词
  if (positiveKeywords.some(keyword => lowerQuestion.includes(keyword))) {
    aiResponse = '是'
  } else if (negativeKeywords.some(keyword => lowerQuestion.includes(keyword))) {
    aiResponse = '否'
  } else if (irrelevantKeywords.some(keyword => lowerQuestion.includes(keyword))) {
    aiResponse = '无关'
  }
  
  // 检查是否接近真相
  if (question.includes('邻居') && question.includes('提醒')) {
    aiResponse = '非常接近了！'
  }
  
  // 添加AI消息
  const aiMessage: Message = {
    id: (Date.now() + 1).toString(),
    content: aiResponse,
    sender: 'ai',
    timestamp: new Date().toISOString()
  }
  messages.value.push(aiMessage)
  
  // 更新回合数
  currentTurn.value++
  
  // 检查游戏状态
  checkGameStatus(question)
  
  // 滚动到底部
  scrollToBottom()
}

// 检查游戏状态
const checkGameStatus = (question: string) => {
  // 模拟判断是否猜对
  if (question.includes('邻居') && question.includes('窗户') && question.includes('提醒')) {
    gameStatus.value = 'won'
    showSolution.value = true
    
    // 添加胜利消息
    const winMessage: Message = {
      id: (Date.now() + 2).toString(),
      content: '恭喜你猜对了！你真厉害！',
      sender: 'ai',
      timestamp: new Date().toISOString()
    }
    messages.value.push(winMessage)
  } else if (currentTurn.value > maxTurns) {
    gameStatus.value = 'lost'
    showSolution.value = true
    
    // 添加失败消息
    const loseMessage: Message = {
      id: (Date.now() + 2).toString(),
      content: '很遗憾，回合数用完了。让我告诉你真相...',
      sender: 'ai',
      timestamp: new Date().toISOString()
    }
    messages.value.push(loseMessage)
  }
}

// 放弃游戏并查看答案
const giveUpAndShowSolution = () => {
  showSolution.value = true
  gameStatus.value = 'lost'
}

// 重新开始游戏
const restartGame = () => {
  currentTurn.value = 1
  gameStatus.value = 'playing'
  showSolution.value = false
  messages.value = [
    {
      id: '1',
      content: `欢迎回到海龟汤游戏！\n今天的题目是：${soup.value?.description}\n你可以通过提问来推测真相，我只能回答"是"、"否"或"无关"。\n开始你的推理吧！`,
      sender: 'ai',
      timestamp: new Date().toISOString()
    }
  ]
}

// 返回主页
const goToHome = () => {
  router.push('/')
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    const chatContainer = document.querySelector('.chat-messages')
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  }, 100)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSoupDetail()
})

// 计算属性
const isGameActive = computed(() => gameStatus.value === 'playing' && currentTurn.value <= maxTurns && !showSolution.value)
const progressPercentage = computed(() => (currentTurn.value - 1) / maxTurns * 100)
const gameResultText = computed(() => {
  if (gameStatus.value === 'won') return '恭喜你赢了！'
  if (gameStatus.value === 'lost') return '游戏结束'
  return '游戏进行中'
})
</script>

<template>
  <div class="game-page">
    <div class="game-container">
      <!-- 游戏头部 -->
      <div class="game-header">
        <button class="back-btn" @click="goToHome">
          <i>←</i> 返回
        </button>
        <h1 v-if="soup">{{ soup.title }}</h1>
        <div class="game-info">
          <span :class="['difficulty', soup?.difficulty]">
            {{ soup?.difficulty === 'easy' ? '简单' : soup?.difficulty === 'medium' ? '中等' : '困难' }}
          </span>
          <span class="turns">
            回合: {{ currentTurn }}/{{ maxTurns }}
          </span>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <p>游戏加载中...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <p>{{ error }}</p>
        <button class="btn-primary" @click="fetchSoupDetail">重试</button>
      </div>

      <!-- 游戏内容 -->
      <div v-else class="game-content">
        <!-- 进度条 -->
        <div class="progress-container">
          <div 
            class="progress-bar" 
            :style="{ width: progressPercentage + '%' }"
            :class="{
              'progress-winning': gameStatus === 'won',
              'progress-losing': gameStatus === 'lost'
            }"
          ></div>
        </div>

        <!-- 聊天区域 -->
        <div class="chat-container">
          <div class="chat-messages">
            <div
              v-for="message in messages"
              :key="message.id"
              :class="['message', message.sender]"
            >
              <div class="message-content">
                {{ message.content }}
              </div>
              <div class="message-time">
                {{ new Date(message.timestamp).toLocaleTimeString('zh-CN', { 
                  hour: '2-digit', 
                  minute: '2-digit' 
                }) }}
              </div>
            </div>

            <!-- 显示答案 -->
            <div v-if="showSolution && soup" class="solution-container">
              <h3>汤底揭晓</h3>
              <p>{{ soup.solution }}</p>
            </div>
          </div>

          <!-- 输入区域 -->
          <div v-if="isGameActive" class="chat-input-container">
            <input
              v-model="inputMessage"
              type="text"
              placeholder="输入你的问题..."
              class="chat-input"
              @keyup.enter="sendQuestion"
            />
            <button class="send-btn" @click="sendQuestion" :disabled="!inputMessage.trim()">
              发送
            </button>
          </div>

          <!-- 游戏结束操作 -->
          <div v-else class="game-actions">
            <button class="btn-primary" @click="restartGame">
              重新开始
            </button>
            <button class="btn-secondary" @click="goToHome">
              返回主页
            </button>
          </div>
        </div>

        <!-- 放弃游戏按钮 -->
        <button 
          v-if="isGameActive" 
          class="give-up-btn" 
          @click="giveUpAndShowSolution"
        >
          放弃并查看答案
        </button>

        <!-- 游戏结果提示 -->
        <div 
          v-if="gameStatus !== 'playing'" 
          class="game-result"
          :class="gameStatus"
        >
          {{ gameResultText }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.game-page {
  min-height: calc(100vh - 120px);
  background-color: #f5f7fa;
  padding: 20px 0;
}

.game-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 游戏头部 */
.game-header {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 16px;
}

.back-btn:hover {
  background-color: #f0f0f0;
  color: #333;
}

.game-header h1 {
  font-size: 24px;
  color: #262626;
  margin: 0;
  flex: 1;
}

.game-info {
  display: flex;
  gap: 12px;
  align-items: center;
}

.difficulty {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.difficulty.easy {
  background-color: #f6ffed;
  color: #52c41a;
}

.difficulty.medium {
  background-color: #fffbe6;
  color: #faad14;
}

.difficulty.hard {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.turns {
  color: #666;
  font-size: 14px;
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  background: white;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  color: #666;
}

/* 游戏内容 */
.game-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  position: relative;
}

/* 进度条 */
.progress-container {
  height: 6px;
  background-color: #f0f0f0;
  border-radius: 3px 3px 0 0;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background-color: #1890ff;
  transition: width 0.3s, background-color 0.3s;
}

.progress-winning {
  background-color: #52c41a;
}

.progress-losing {
  background-color: #ff4d4f;
}

/* 聊天区域 */
.chat-container {
  height: calc(70vh - 180px);
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  max-width: 80%;
  display: flex;
  flex-direction: column;
}

.message.user {
  align-self: flex-end;
}

.message.ai {
  align-self: flex-start;
}

.message-content {
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.5;
  word-wrap: break-word;
}

.message.user .message-content {
  background-color: #1890ff;
  color: white;
}

.message.ai .message-content {
  background-color: #f0f0f0;
  color: #333;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  padding: 0 4px;
}

.message.user .message-time {
  text-align: right;
}

/* 答案显示 */
.solution-container {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 8px;
  padding: 20px;
  margin-top: 16px;
}

.solution-container h3 {
  color: #52c41a;
  margin: 0 0 12px 0;
  font-size: 18px;
}

.solution-container p {
  color: #333;
  line-height: 1.6;
  margin: 0;
}

/* 输入区域 */
.chat-input-container {
  display: flex;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.chat-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.chat-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.send-btn {
  padding: 12px 24px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-btn:hover:not(:disabled) {
  background-color: #40a9ff;
}

.send-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 游戏操作按钮 */
.game-actions {
  display: flex;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

/* 放弃游戏按钮 */
.give-up-btn {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 6px 12px;
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.give-up-btn:hover {
  background-color: #ff4d4f;
  color: white;
}

/* 游戏结果提示 */
.game-result {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 16px 32px;
  border-radius: 8px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  animation: fadeIn 0.5s ease;
}

.game-result.won {
  background-color: rgba(82, 196, 26, 0.9);
  color: white;
}

.game-result.lost {
  background-color: rgba(255, 77, 79, 0.9);
  color: white;
}

/* 按钮样式 */
.btn-primary {
  flex: 1;
  padding: 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #40a9ff;
}

.btn-secondary {
  flex: 1;
  padding: 12px;
  background-color: white;
  color: #1890ff;
  border: 1px solid #1890ff;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background-color: #e6f7ff;
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .game-header {
    flex-wrap: wrap;
  }
  
  .game-header h1 {
    font-size: 20px;
    width: 100%;
    order: 2;
  }
  
  .game-info {
    order: 3;
    width: 100%;
  }
  
  .message {
    max-width: 90%;
  }
  
  .chat-container {
    height: calc(70vh - 220px);
  }
}

@media (max-width: 480px) {
  .game-container {
    padding: 0 16px;
  }
  
  .chat-messages {
    padding: 16px;
  }
  
  .chat-input-container {
    padding: 16px;
  }
  
  .give-up-btn {
    position: relative;
    top: auto;
    right: auto;
    margin: 0 auto 20px;
    display: block;
  }
}
</style>